/**
 * MineAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using MineAdmin.
 *
 * @Author X.Mo<root@imoi.cn>
 * @Link   https://github.com/mineadmin
 */
import type { MaProTableColumns, MaProTableExpose } from "@mineadmin/pro-table";
import type { UseDialogExpose } from "@/hooks/useDialog.ts";

import defaultAvatar from "@/assets/images/defaultAvatar.jpg";
import { ElTag } from "element-plus";
import { useMessage } from "@/hooks/useMessage.ts";
import { ResultCode } from "@/utils/ResultCode.ts";
import hasAuth from "@/utils/permission/hasAuth.ts";
import { deleteByIds } from "$/attractions/broadcast/api/broadcastExecutionLog.ts";
import { page as getPlans } from "$/attractions/broadcast/api/broadcastPlans.ts";
import { page as getDevices } from "$/attractions/broadcast/api/broadcastDevices.ts";

export default function getTableColumns(
  dialog: UseDialogExpose,
  formRef: any,
  t: any
): MaProTableColumns[] {
  const msg = useMessage();

  const plansList = ref<any[]>([]);
  const devicesList = ref<any[]>([]);

  onMounted(async () => {
    // 获取计划列表
    const plansResponse = await getPlans({});
    if (
      plansResponse.code === 200 &&
      plansResponse.data &&
      plansResponse.data.list
    ) {
      plansList.value = plansResponse.data.list;
    }

    // 获取设备列表
    const devicesResponse = await getDevices({});
    if (
      devicesResponse.code === 200 &&
      devicesResponse.data &&
      devicesResponse.data.list
    ) {
      devicesList.value = devicesResponse.data.list;
    }
  });

  return [
    {
      type: "selection",
      showOverflowTooltip: false,
      label: () => t("crud.selection"),
    },
    {
      label: "计划名称",
      prop: "plan_id",
      renderProps: { multiple: false },
      cellRender: ({ row }) => {
        const planName = plansList.value.find(
          (plan) => plan.id === row.plan_id
        );
        return planName?.plan_name || `计划${row.plan_id}`;
      },
    },
    {
      label: "设备名称",
      prop: "device_id",
      renderProps: { multiple: false },
      cellRender: ({ row }) => {
        console.log("*************", devicesList.value);

        const deviceName = devicesList.value.find(
          (device) => device.id === row.device_id
        );
        return deviceName?.device_name || `设备${row.device_id}`;
      },
      width: 200,
    },
    {
      label: "执行类型",
      prop: "execution_type",
      cellRender: ({ row }) => {
        const statusMap = {
          1: { text: "计划执行", type: "success" },
          2: { text: "手动执行", type: "warning" },
          3: { text: "应急执行", type: "info" },
        };
        const status = statusMap[row.execution_type] || {
          text: "未知",
          type: "info",
        };
        return h(ElTag, { type: status.type }, () => status.text);
      },
    },
    { label: "广播文件", prop: "file" },
    {
      label: "广播文件",
      prop: "file",
      multiple: false,
      cellRender: ({ row }) => {
        if (!row?.file) {
          return <span style={{ color: "#999" }}>无文件</span>;
        }

        // 获取API基础URL
        const env = import.meta.env;
        const baseUrl =
          env.VITE_OPEN_PROXY === "true"
            ? env.VITE_PROXY_PREFIX
            : env.VITE_APP_API_BASEURL;
        const fileUrl = `${baseUrl}${row.file}`;

        return (
          <el-link
            onClick={() => {
              // 创建下载链接
              const link = document.createElement("a");
              link.href = fileUrl;
              link.download = row.file.split("/").pop() || "资质文件";
              document.body.appendChild(link);
              link.click();
              document.body.removeChild(link);
            }}
            type="primary"
          >
            下载文件
          </el-link>
        );
      },
    },
    { label: "广播内容", prop: "broadcast_content" },
    { label: "开始播放时间", prop: "start_time", mode: "date", showTime: true },
    { label: "结束播放时间", prop: "end_time", mode: "date", showTime: true },
    { label: "实际执行时长（秒）", prop: "actual_duration" },
    {
      label: "执行状态",
      prop: "execution_status",
      cellRender: ({ row }) => {
        const statusMap = {
          1: { text: "执行中", type: "success" },
          2: { text: "已完成", type: "warning" },
          3: { text: "失败", type: "danger" },
        };
        const status = statusMap[row.execution_status] || {
          text: "未知",
          type: "info",
        };
        return h(ElTag, { type: status.type }, () => status.text);
      },
    },
    { label: "失败原因", prop: "fail_reason" },
    { label: "播放音量", prop: "volume_level" },
    { label: "备注", prop: "remark" },
    {
      type: "operation",
      label: () => t("crud.operation"),
      fixed: "right",
      operationConfigure: {
        actions: [
          // {
          //   name: "edit",
          //   icon: "material-symbols:person-edit",
          //   show: ({ row }) =>
          //     hasAuth("broadcast_log:broadcastLog:update"),
          //   text: () => t("crud.edit"),
          //   onClick: ({ row }) => {
          //     dialog.setTitle(t("crud.edit"));
          //     dialog.open({ formType: "edit", data: row });
          //   },
          // },
          {
            name: "del",
            icon: "mdi:delete",
            text: () => t("crud.delete"),
            show: ({ row }) => hasAuth("broadcast_log:broadcastLog:delete"),
            onClick: ({ row }, proxy: MaProTableExpose) => {
              msg.delConfirm(t("crud.delDataMessage")).then(async () => {
                const response = await deleteByIds([row.id]);
                if (response.code === ResultCode.SUCCESS) {
                  msg.success(t("crud.delSuccess"));
                  proxy.refresh();
                }
              });
            },
          },
        ],
      },
    },
  ];
}
